<template>
	<view>
		<authBuitton v-if="isLogin" :follow="follow" @followCampany="followCampany" @openAuth="openAuth"
			:isAuthBtn="isAuthBtn"></authBuitton>
		<view class="company-detail">
			<view class="top-card">
				<view class="top-card-bt">
					<view class="top-card-left">
						<view>{{ detailInfo.enterpriseName || '' }}</view>
						<view>创建时间：{{ detailInfo.createTime ? detailInfo.createTime.slice(0, 10) : '' }}</view>
					</view>
					<!-- <button class="top-card-right" open-type="share">转发报告</button> -->
				</view>
			</view>
			<view class="detailContent"
				:style="{ 'padding-top': !detailInfo.dateStatus && isDemo == '' ? '50rpx' : '0' }">
				<view class="paddingL15"
					v-if="!detailInfo.dateStatus && isDemo == '' && detailInfo.source != null && detailInfo.source != 'common'">
					<view class="row topType paddingL15">
						<view class="text">您正在查看的历史数据可能有更新，建议重新查询以获取最新信息</view>
						<button :loading="searchLoading" :disabled="searchLoading" class="btn"
							@click="refreash(detailInfo)">重新查询</button>
					</view>
				</view>
				<view class="paddingL15">
					<tab :defaultIndex="current" :tabStyle="' background-color: #fff;'" :tabList="tablist"
						:color="'#488AFD'" @click="tabClick" @changeTime="changeTime">
					</tab>
				</view>
			</view>
		</view>
		<view style="background-color: white; padding-bottom: 180rpx;" :style="{ marginTop: height + 'px' }"
			v-if="isAuthSee && isLogin">
			<base-information ref="baseInformationRef" :key="baseInfoKey" v-if="current == 0" :taskId="taskId"
				:shareCode="shareCode" @getInfo="getInfo" @authBtn="authBtn" :isDemo="isDemo"></base-information>
			<tax-information ref="taxInformationRef" v-if="current == 1" :taskId="taskId" :shareCode="shareCode"
				:isDemo="isDemo"></tax-information>
			<invoice-information ref="invoiceInformationRef" v-if="current == 2" :taskId="taskId" :shareCode="shareCode"
				:isDemo="isDemo"></invoice-information>
			<bussiness-information ref="bussinessInformationRef" v-if="current == 3" :taskId="taskId"
				:shareCode="shareCode" :isDemo="isDemo"></bussiness-information>
			<shoper v-if="current == 4" ref="shoperRef" :taskId="taskId" :shareCode="shareCode" :isDemo="isDemo">
			</shoper>
		</view>


		<view class="footer-btnBox" v-if="isLogin">
			<button :loading="downloading" @click="exportPDF()" :disabled="!isAuthBtn || downloading"
				style="margin-right: 10rpx;" class="btn">导出PDF</button>
			<button style="margin-left: 10rpx;" class="btn" open-type="share">分享报告</button>
		</view>

		<!-- 没有数据权限 -->
		<view style="position: fixed; width: 100%; top: 50%; left: 50%; transform: translate(-50%, -50%);"
			v-if="!isAuthSee">
			<empty emptyTitle="暂无数据权限"></empty>
		</view>
		<!-- 分享到朋友圈 -->
		<uni-popup ref="popup" :maskClick="false" :maskBackgroundColor="'rgba(0, 0, 0, 0.6)'">
			<view @click="closePop" style="margin-top: -550rpx; margin-left: 60rpx">
				<image src="/pagesWater/static/guide.png"></image>
			</view>
		</uni-popup>

		<!-- 重新查询 -->
		<againSearchPupupVue ref="againSearchRef"></againSearchPupupVue>
		<setPageAuth @getDetail="getDetail" ref="setPageAuth"></setPageAuth>

		<view class="scroll-t" v-if="isScrollTop" @click="scroTop">
			<uni-icons type="up" color="#fff" size="24"></uni-icons>
		</view>
		<authorize @onLoadFun="onLoadFun" :isShowAuth="isShowAuth" @authColse="authColse"></authorize>
	</view>
</template>

<script>
import BaseInformation from "@/pagesWater/taxSearch/components/baseInformation.vue";
import TaxInformation from "@/pagesWater/taxSearch/components/taxInformation.vue";
import InvoiceInformation from "@/pagesWater/taxSearch/components/invoiceInformation.vue";
import BussinessInformation from "@/pagesWater/taxSearch/components/bussinessInformation.vue";
import shoper from "@/pagesWater/taxSearch/components/shoper.vue";
import authBuitton from "./components/authBuitton.vue";
import setPageAuth from "./components/setPageAuth.vue";
import againSearchPupupVue from "./components/againSearchPupup.vue";
import residenceTime from "@/mixins/residenceTime";
import Authorize from "@/components/Authorize.vue";
import { getTaxPdf } from '@/api/water'
import {
	detailInfo
} from "../options";
import {
	getReturnSearchTax,
	followEnterpriseApi
} from "@/api/user";
import {
	mapGetters
} from "vuex";
import cache from "@/utils/cache";
import Empty from '../../components/empty/empty.vue';
import { HTTP_REQUEST_URL, APP_ID, H5_APP_ID } from "@/config/app";
import { openEnterpriseTypeSubscribe } from '@/utils/SubscribeMessage.js'
import Routine from "@/libs/routine";
export default {
	mixins: [residenceTime],
	components: {
		BussinessInformation,
		InvoiceInformation,
		TaxInformation,
		BaseInformation,
		shoper,
		authBuitton,
		setPageAuth,
		Authorize,
		againSearchPupupVue,
		Empty
	},
	data() {
		return {
			tablist: ["基本信息", "纳税信息", "发票信息", "供应商信息", "工商司法"],
			current: 0,
			taskId: "", //详情查询使用taskid，企业id已废弃
			shareCode: "",
			detailInfo: {},
			isShowAuth: false,
			baseInfoKey: 0,
			userinfo: null,
			isDemo: '',
			searchLoading: false,
			height: 0,
			scrollTop: 0,
			isScrollTop: false,
			isAuthBtn: false, //是否有设置权限按钮
			isAuthSee: true, //处理403 是否看数据
			downloading: false,
			follow: false,
			viewParam: {}
		};
	},
	onPageScroll(e) {
		if (e.scrollTop > this.scrollTop) {
			this.isScrollTop = true
		} else {
			this.isScrollTop = false
		}
	},
	computed: {
		...mapGetters(["isLogin", "phoneNumber", "token"]),
	},
	onLoad(options) {

		global.spid = 0;
		if (options.spreadUid) {
			global.spid = options.spreadUid;
		}
		if (options.id) {
			this.taskId = options.id;
		}
		if (options.shareCode) {
			this.shareCode = options.shareCode;
		}
		this.userinfo = cache.get("USER_INFO") ? JSON.parse(cache.get("USER_INFO")) : {};
		this.isDemo = options?.isDemo || ''
		if (this.isDemo) {
			this.$nextTick(() => {
				this.getContainerHeight();
			});
		}
	},
	async onShow() {
		// 下面的暂时注释
		if (this.isLogin) {
			if (this.shareCode) {
				// #ifdef H5
				this.baseInfoKey++
				// #endif
			} else {
				this.detailInfo = detailInfo.data;
			}
			// #ifdef H5
			this.isShowAuth = false
			this.setWXConfig()
			// #endif
		} else {

			// #ifdef MP-WEIXIN
			this.isShowAuth = true
			// #endif

			// #ifdef H5
			if (!this.isLogin) {
				if (Routine.isWeixin()) {
					this.isShowAuth = true
					// await this.$wxAuthorize();
				} else {
					this.isShowAuth = true
				}
			}
			// #endif
		}
		this.getSystemInfo();
	},
	// #ifdef MP-WEIXIN
	onShareAppMessage: function (res) {

		return {
			imageUrl: '../static/resultShareBg.png',
			title: '助融报告',
			path: `pagesWater/taxSearch/companyDetail?shareCode=${this.shareCode}`,
		}
	},
	// #endif
	methods: {
		getSystemInfo() {
			var UA = navigator.userAgent,
				isAndroid = /android|adr/gi.test(UA),
				isIOS = /iphone|ipod|ipad/gi.test(UA) && !isAndroid,
				isBlackBerry = /BlackBerry/i.test(UA),
				isWindowPhone = /IEMobile/i.test(UA),
				isMobile = isAndroid || isIOS || isBlackBerry || isWindowPhone;
			this.viewParam = {
				isAndroid: isAndroid,
				isIOS: isIOS,
				isMobile: isMobile,
				isWeixin: /MicroMessenger/gi.test(UA),
				isQQ: /QQ/gi.test(UA),
			};
		},
		followCampany(v) {
			let params = {
				enterpriseId: this.detailInfo.enterpriseId,
				action: v,
				appId: APP_ID
			}
			if (v == 1) {
				openEnterpriseTypeSubscribe().then(() => {
					followEnterpriseApi(params).then(res => {
						if (res.data) this.follow = !this.follow
					})
				})
			} else {
				followEnterpriseApi(params).then(res => {
					if (res.data) this.follow = !this.follow
				})
			}


		},
		exportPDF() {
			this.downloading = true
			let url = HTTP_REQUEST_URL.replace("portal", "taxReport")

			let params = {
				pageUrl: `${url}?shareCode=${this.shareCode}`,
			}
			let that = this
			getTaxPdf(params).then(res => {
				// #ifdef H5
				if (this.viewParam.isWeixin) {
					console.log(res);

					// 安卓浏览器
					if (this.viewParam.isAndroid) {
						var iframe = document.createElement("iframe");
						iframe.style.display = "none";
						iframe.src = res.data;
						document.body.appendChild(iframe);
						iframe.click();
					}
					// IOS浏览器
					else if (this.viewParam.isIOS) {
						const x = new XMLHttpRequest();
						x.responseType = "blob";
						x.open("GET", res.data, true);
						x.send();
						x.onload = () => {
							const downloadElement = document.createElement("a");
							const href = window.URL.createObjectURL(x.response);
							downloadElement.href = href;
							downloadElement.download = item?.filename.split('_')[0] + '企业分析报告';
							document.body.appendChild(downloadElement);
							downloadElement.click();
							document.body.removeChild(downloadElement);
							window.URL.revokeObjectURL(href);
							that.downloading = false
						};
					}
				}
				// 非微信内置浏览器
				else {
					window.location.replace(res.data);
					that.downloading = false
				}
				// #endif
				// #ifdef MP-WEIXIN
				uni.downloadFile({
					url: res.data,
					success: function (res) {
						var filePath = res.tempFilePath;
						// that.downloading = false
						uni.openDocument({
							filePath: filePath,
							showMenu: true,
							success: function (res) {
								that.downloading = false
								console.log('打开文档成功');
							}
						});
					}
				});
				// #endif

			}).finally(() => {

			}).catch(() => {
				this.downloading = false
			})
			console.log("params", params)
		},
		authBtn(v) {
			this.isAuthBtn = v.visibleConfigButton
			this.isAuthSee = v ? true : false
			this.$nextTick(() => {
				this.getContainerHeight();
			})
		},
		getDetail() {

			this.current = 0
			this.scroTop()
			this.$refs.baseInformationRef.getShareDetail()
		},
		scroTop() {
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 100
			})
		},
		pageViewTrack(stayTime) {
			const route = this.$util.getCurrentRoute()
			let params = {
				Um_Key_SourcePage: route.path,
				Um_Key_Duration: stayTime,
			}
			this.$umaTrack.pageViewTrack(params)
		},
		onLoadFun() {
			this.isShowAuth = false
			this.$refs.baseInformationRef.getShareDetail()
		},

		authColse() {
			this.$util.Tips('当前功能必须要授权登录才能访问，退出请点击右上角退出按钮')
		},
		openAuth(v) {
			this.$refs.setPageAuth.openAuth(this.detailInfo)
		},
		getContainerHeight() {
			let that = this;
			let info = uni.createSelectorQuery().select(".company-detail");
			info.boundingClientRect(function (data) {
				// #ifdef MP-WEIXIN
				that.height = data.height
				// #endif
				// #ifdef H5
				that.height = data.height
				// #endif
			})
				.exec();
		},
		refreash(obj) {


			// tax=914201037680567654&companyName=武汉金正合融资担保有限公司&provinceName=hubei&provinceId=17

			uni.navigateTo({
				url: "/pagesWater/taxSearch/index?taxpayerName=" + obj.enterpriseName,
			});

			return 
			let params = {
				taskId: this.detailInfo.taskId,
				creditCode: this.detailInfo.creditCode
			}
			this.searchLoading = true
			getReturnSearchTax(params).then(res => {
				if (!res.data.needVerifyCode) {
					this.$util.Tips({
						title: res.message
					}, () => {
						uni.switchTab({
							url: '/pages/reportList/index'
						})
					})
				}
				if (res.data.code == 0 && res.data.needVerifyCode) {
					const sendCodeForm = {
						account: this.detailInfo.phone
					}
					const codeForm = {
						province: res.data.queryTaskVo.province,
						creditCode: this.detailInfo.creditCode,
						uuid: res.data.uuid,
						account: res.data.queryTaskVo.phone
					}
					this.$refs.againSearchRef.open(sendCodeForm, codeForm, this.detailInfo)
					// this.$refs.sendCodeRef.open()
				}
			}).finally(() => {
				this.searchLoading = false
			})


			let paramsPageClick = {
				Um_Key_ButtonName: '重新查询',
				Um_Key_SourcePage: `报告详情-${this.detailInfo.shareCode}`,
			}
			this.$umaTrack.pageClickTrack(paramsPageClick)

		},

		closePop() {
			this.$refs.popup.close();
		},

		copyUrl() {
			// this.$nextTick(() => {
			// 	this.$refs.popup.open("center");
			// });

		},
		tabClick(val) {
			this.current = val;
			this.scroTop()
			let params = {
				Um_Key_ButtonName: this.tablist[val],
				Um_Key_SourcePage: `报告详情-${this.detailInfo.shareCode}`,
			}
			this.$umaTrack.pageClickTrack(params)
		},

		//记录切换时间
		changeTime(valObj) {
			const route = this.$util.getCurrentRoute()
			let Um_Key_PageCategory = this.shareCode + '-' + this.tablist[valObj.oldCurrent]
			let params = {
				Um_Key_PageCategory,
				Um_Key_SourcePage: route.path,
				Um_Key_Duration: valObj.time,
			}
			this.$umaTrack.pageViewTrack(params)

		},

		getInfo(val) {
			this.detailInfo = val
			this.follow = val.follow
			// #ifdef H5
			this.setWXConfig()
			// #endif
		},
		setWXConfig() {
			let opt = {
				title: this.detailInfo.enterpriseName || '',
				desc: "点击查看",
				link: this.$util.getPageUrl({
					shareCode: this.shareCode,
					spreadUid: this.userinfo?.id || '',
				},
					"pagesWater/taxSearch/companyDetail"
				),
			};
			// console.log("link", opt);
			this.$util.setWXConfig(opt);
		},
	},
};
</script>

<style lang="scss">
.company-detail {
	position: fixed;
	width: 100%;
	left: 0;
	top: 0;
	z-index: 10;
}

.scroll-t {
	position: fixed;
	bottom: 200rpx;
	right: 50rpx;
	width: 80rpx;
	height: 80rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 50%;
	background-color: #e1e1e1;
	z-index: 10;
}

.top-card {
	width: 100%;
	background: #488AFD;

	.top-card-bt {
		display: flex;
		justify-content: space-between;
		align-items: center;
		/* #ifdef MP-WEIXIN */
		padding: 180rpx 30rpx 90rpx;
		/* #endif */
		/* #ifdef H5 */
		padding: 120rpx 30rpx 90rpx;
		/* #endif */
	}

	.top-card-left {
		// width: 68%;

		>view {
			&:nth-child(1) {
				font-weight: 600;
				font-size: 36rpx;
				color: #FFFFFF;
				margin-bottom: 10rpx;
			}

			&:nth-child(2) {
				font-weight: 400;
				font-size: 24rpx;
				color: #FFFFFF;
				margin-top: 10rpx;
			}
		}
	}

	.top-card-right {
		// width: 35%;
		background-color: #fff;
		width: 190rpx;
		height: 60rpx;
		font-size: 26rpx;
		line-height: 60rpx;
		border-radius: 30rpx;
		color: #488AFD;
	}
}

.detailContent {
	z-index: 9;
	width: 100%;
	background: white;
	border-radius: 30rpx 30rpx 0 0;
	height: auto;
	margin-top: -30rpx;
	position: relative;
	padding-top: 50rpx;

	.topType {
		width: 100%;
		height: 128rpx;
		box-shadow: 0rpx 0rpx 8rpx 0rpx rgba(0, 41, 113, 0.2);
		background: rgba(0, 41, 113, 0.20);
		border-radius: 16rpx;

		.text {
			width: 78%;
			color: #555555;
		}

		.btn {
			width: 180rpx;
			height: 70rpx;
			line-height: 70rpx;
			color: #FFFFFF;
			background: #488AFD;
			white-space: nowrap;
			text-align: center;
			border-radius: 30rpx;
			font-size: 26rpx;
		}
	}
}

.footer-btnBox {
	position: fixed;
	left: 0;
	bottom: 0;
	width: 750rpx;
	height: 166rpx;
	background: #FFFFFF;
	box-shadow: 0rpx -2rpx 6rpx 0rpx rgba(0, 0, 0, 0.05);
	display: flex;
	padding-bottom: 30rpx;
	padding-top: 30rpx;
	z-index: 98;

	.btn {
		width: 240rpx;
		height: 78rpx;
		background: #276FF7;
		border-radius: 12rpx;
		text-align: center;
		line-height: 78rpx;
		color: #fff;
	}
}
</style>